package demo;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 锁绑定多个条件 Condition 可指定唤醒
 * @author Javen
 */
@Slf4j
public class ConditionDemo {

    private int number = 1;
    private final Lock lock = new ReentrantLock();
    private final Condition a = lock.newCondition();
    private final Condition b = lock.newCondition();
    private final Condition c = lock.newCondition();

    public void print5() {
        lock.lock();
        try {
            // 判断
            while (number != 1) {
                // 等待
                a.await();
            }

            // 操作
            number = 2;
            for (int i = 0; i < 5; i++) {
                log.info(" {} number: {} ", Thread.currentThread().getName(), i);
            }
            // 通知唤醒
            b.signalAll();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void print10() {
        lock.lock();
        try {
            // 判断
            while (number != 2) {
                // 等待
                b.await();
            }

            // 操作
            number = 3;
            for (int i = 0; i < 10; i++) {
                log.info(" {} number: {} ", Thread.currentThread().getName(), i);
            }
            // 通知唤醒
            c.signalAll();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }


    public void print15() {
        lock.lock();
        try {
            // 判断
            while (number != 3) {
                // 等待
                c.await();
            }

            // 操作
            number = 1;
            for (int i = 0; i < 15; i++) {
                log.info(" {} number: {} ", Thread.currentThread().getName(), i);
            }
            // 通知唤醒
            a.signalAll();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public static void main(String[] args) {
        final ConditionDemo conditionDemo = new ConditionDemo();

         new Thread(() -> {
             for (int i = 0; i < 10; i++) {
                 conditionDemo.print5();
             }
         }).start();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                conditionDemo.print10();
            }
        }).start();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                conditionDemo.print15();
            }
        }).start();
    }
}
